﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;

namespace TooltracePC
{
    public partial class frmMain : Form
    {
        public static Hashtable _hshCgf = new Hashtable();
        dgv dgvObject = new dgv();
        ServerNet netServer = new ServerNet();

        public frmMain()
        {
            InitializeComponent();
            //ListBox.CheckForIllegalCrossThreadCalls = false;
            TextBox.CheckForIllegalCrossThreadCalls = false;
            //ToolStripProgressBar.CheckForIllegalCrossThreadCalls = false;
            //Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            //this.Owner.Hide();
            tmMain.Enabled = true;
            btnSync.Enabled = false;
            dbTool Tooldb = new dbTool();
            tsToolCount.Text =  Tooldb.getToolCount().ToString();

            dbUser Userdb = new dbUser();
            tsUserCount.Text = Userdb.getUserCount().ToString();

            _loadCfg();

            if (_hshCgf.Contains("Debug"))
            {
                if (_hshCgf["Debug"].ToString() == "0")
                {
                    //tbDebug.Visible = false;
                 }
            }

            if (_hshCgf.Contains("Port"))
            {
                int port = int.Parse(_hshCgf["Port"].ToString());
                ServerNet._port = port;
            }
            
            DataTable dtU = new DataTable();
            dtU = Userdb.getAll();
           
            for (int i = 0; i < dtU.Rows.Count; i++)
            {
                cbMan.Items.Add(dtU.Rows[i]["UserName"].ToString());
            }


            dbSync syncDB = new dbSync();
            DataTable dt = null;
            dt = syncDB.getAll();
            dgvObject.setDgv(dgvSync);
            dgvObject.setgDgv(dgvSync);//save global
            dgvObject.setDataSource(dt);
            dgvObject.setFormatComm();
            dgvObject.setFormatSync();

            //net
            netServer.init(tbMsg, tspbNet);

            netServer.Listen();
            tsLocalInfo.Text = "本机IP:" + netServer.getLocalIP() + ", 服务端口:" + _hshCgf["Port"].ToString();
        }


        //get configs
        private void _loadCfg()
        {
            //load config
            dbConfig dbConfigObject = new dbConfig();
            DataTable dtCfg = null;
            dtCfg = dbConfigObject.getAll();

            for(int i = 0; i < dtCfg.Rows.Count; i++)
            {
                _hshCgf.Add(dtCfg.Rows[i]["ConfigName"].ToString(), dtCfg.Rows[i]["ConfigValue"].ToString());
            }

        }


        private void frmMain_FormClose(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            
            
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {

        }

       

        private void btnTool_Click(object sender, EventArgs e)
        {
           
        }

        private void mQuit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void toolStripStatusLabel5_Click(object sender, EventArgs e)
        {

        }

        private void tbpData_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(tbpData.SelectedTab == tpToolData)//tool
            {
                dbTool ToolDb = new dbTool();
                DataTable dtTool = new DataTable();
                dtTool = ToolDb.getAll();

                dgvObject.setDgv(dgvTool);
                dgvObject.setDataSource(dtTool);
                dgvObject.setFormatComm();
                dgvObject.setFormatTool();
            }
            else if (tbpData.SelectedTab == tpStaffData) //staff
            {
                dbUser StafflDb = new dbUser();
                DataTable dtTool = new DataTable();
                dtTool = StafflDb.getAll();

                dgvObject.setDgv(dgvStaff);
                dgvObject.setDataSource(dtTool);
                dgvObject.setFormatComm();
                dgvObject.setFormatStaff();
            }
            else
            {
                dbSync syncDB = new dbSync();
                DataTable dt = new DataTable();
                dt = syncDB.getAll();
                dgvObject.setDgv(dgvSync);
                dgvObject.setDataSource(dt);
                dgvObject.setFormatComm();
                dgvObject.setFormatSync();
            }

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }

        private void btnSearchTool_Click(object sender, EventArgs e)
        {
            string keyword = this.tbKeyWordTool.Text;
            dbTool ToolDb = new dbTool();
            DataTable dtTool = null;

            if (string.IsNullOrEmpty(keyword))
            {
                dtTool = ToolDb.getAll();
            }
            else
            {
                dtTool = ToolDb.getByName(keyword);
            }

            dgvObject.setDataSource(dtTool);
        }


        //set data grid view formart
        private void dgvTool_DataSourceChanged(object sender, EventArgs e)
        {
            dgvObject.setRowFormat();
        }



        private void btnReflashTool_Click(object sender, EventArgs e)
        {
            dbTool ToolDb = new dbTool();
            DataTable dtTool = null;
            dtTool = ToolDb.getAll();
            dgvObject.setDataSource(dtTool);
            //dgvTool.DataSource = dtTool;
        }



        private void dgvTool_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.RowIndex == -1)
            {
                return;
            }
            dgvObject.setSelectID(dgvTool.Rows[e.RowIndex].Cells[0].Value.ToString());
            frmToolAdd frmTool = new frmToolAdd();
            frmTool.ShowDialog(this);

        }

        private void btnAddTool_Click(object sender, EventArgs e)
        {
            dgvObject.setSelectID("0");
            frmToolAdd frmTool = new frmToolAdd();
            frmTool.ShowDialog(this);
        }

        private void btnDeleteTool_Click(object sender, EventArgs e)
        {
            int[] _id = null;
            _id = dgvObject.getSelectedRows();
            if(_id == null || _id.Length == 0)
            {
                MessageBox.Show("请先选择记录", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if(MessageBox.Show("删除后无法恢复，是否继续删除？", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }

            dbTool ToolDb = new dbTool();
            if(ToolDb.deleteDb(_id) == 1)
            {
                DataTable dtTool = null;
                dtTool = ToolDb.getAll();
                dgvObject.setDataSource(dtTool);
            }

            return;
        }


        private void dgvTool_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }


        private void dgvStaff_DataSourceChanged(object sender, EventArgs e)
        {
            dgvObject.setRowFormat();
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void toolStrip1_ItemClicked_1(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void btnSearchStaff_Click(object sender, EventArgs e)
        {
            string keyword = this.tbKeyWordStaff.Text;
            dbUser StafflDb = new dbUser();
            DataTable dtTool = null;

            if (string.IsNullOrEmpty(keyword))
            {
                dtTool = StafflDb.getAll();
            }
            else
            {
                dtTool = StafflDb.getByName(keyword);
            }

            dgvObject.setDataSource(dtTool);
        }

       

        private void btnDelStaff_Click(object sender, EventArgs e)
        {
            int[] _id = null;
            _id = dgvObject.getSelectedRows();
            if (_id == null || _id.Length == 0)
            {
                MessageBox.Show("请先选择记录", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (MessageBox.Show("删除后无法恢复，是否继续删除？", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }

            dbUser UserDb = new dbUser();
            if (UserDb.deleteDb(_id) == 1)
            {
                DataTable dtTool = null;
                dtTool = UserDb.getAll();
                dgvObject.setDataSource(dtTool);
            }

            return;
        }

        private void btnReflashStaff_Click(object sender, EventArgs e)
        {
            dbUser StafflDb = new dbUser();
            DataTable dtTool = null;
            dtTool = StafflDb.getAll();
            dgvObject.setDataSource(dtTool);
        }




        private void btnAddStaff_Click(object sender, EventArgs e)
        {
            dgvObject.setSelectID("0");
            frmUser frmUserUI = new frmUser();
            frmUserUI.ShowDialog(this);
        }




        private void dgvStaff_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {   
            if(e.RowIndex == -1)
            {
                return;
            }
            dgvObject.setSelectID(dgvStaff.Rows[e.RowIndex].Cells[0].Value.ToString());
            frmUser frmUserUI = new frmUser();
            frmUserUI.ShowDialog(this);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
        }

        private void tmMain_Tick(object sender, EventArgs e)
        {
            frmUSB frmUSBUI = new frmUSB();
            if (frmUSBUI.checkConn() == 1)
            {
                tsStatus.Text = "手持设备已连接";
                btnSync.Enabled = true;
            }
            else
            {
                tsStatus.Text = "手持设备未连接";
                btnSync.Enabled = false;
            }

            //net
            tsConnCount.Text = ServerNet._index.ToString();
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //netObject.closeCM();
            Application.Exit();
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            /*string[] files = null;
            files = ucObject.getFileList();
            if (files == null)
            {
                return;
            }
            */
            //for(int i = 0; i < files.Count(); i++)
            //{
            // MessageBox.Show(AppDomain.CurrentDomain.BaseDirectory.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            // }

            frmUSB frmUSBUI = new frmUSB();
            frmUSBUI.setOP(1);
            frmUSBUI.Show(this);

        }

        private void dgvSync_DataSourceChanged(object sender, EventArgs e)
        {
            dgvObject.setSyncRowFormat();
        }

        private void btnSyncFlash_Click(object sender, EventArgs e)
        {
            dbSync syncDB = new dbSync();
            DataTable dt = new DataTable();
            dt = syncDB.getAll();
            dgvObject.setDgv(dgvSync);
            dgvObject.setDataSource(dt);
            //dgvObject.setFormatComm();
            //dgvObject.setFormatSync();
        }

        private void btnSyncSearch_Click(object sender, EventArgs e)
        {
            string CreateMan = cbMan.Text.ToString();
            string strSartDate = "";
            string strEndDate = "";
            dbSync syncDB = new dbSync();
            DataTable dt = new DataTable();
            
            if (string.IsNullOrEmpty(CreateMan) && dpStartDate.Checked == false && dpEndDate.Checked == false)
            {
                MessageBox.Show("请输入搜索条件!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (dpStartDate.Checked)
            {
                strSartDate = dpStartDate.Text.ToString();
            }

            if (dpEndDate.Checked)
            {
                strEndDate = dpEndDate.Text.ToString();
            }

            dt = syncDB.getByManAndDate(CreateMan, strSartDate, strEndDate);
            dgvObject.setDataSource(dt);
        }

        private void dgvSync_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }
            dgvObject.setSelectedFile(dgvSync.Rows[e.RowIndex].Cells[4].Value.ToString());
            frmSyncData frmsyncData = new frmSyncData();
            frmsyncData.ShowDialog(this);
        }

        private void btnPrintTool_Click(object sender, EventArgs e)
        {
            DGVPrinter printer = new DGVPrinter();

            printer.TitleFont = new Font("宋体", 12, FontStyle.Bold);

            printer.Title = "工具资料";
            printer.SubTitle = "----------------";
            printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            printer.PageNumbers = true;
            printer.ShowTotalPageNumber = true;
            printer.PageNumberInHeader = false;
            printer.PorportionalColumns = true;
            printer.HeaderCellAlignment = StringAlignment.Near;
            printer.Footer = "";
            printer.FooterSpacing = 15;
            printer.PageSeparator = " / ";
            printer.PageText = "页";

            printer.PrintPreviewDataGridView(dgvTool);
        }

        private void btnPrintStaff_Click(object sender, EventArgs e)
        {
            DGVPrinter printer = new DGVPrinter();

            printer.TitleFont = new Font("宋体", 12, FontStyle.Bold);

            printer.Title = "员工资料";
            printer.SubTitle = "----------------";
            printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            printer.PageNumbers = true;
            printer.ShowTotalPageNumber = true;
            printer.PageNumberInHeader = false;
            printer.PorportionalColumns = true;
            printer.HeaderCellAlignment = StringAlignment.Near;
            printer.Footer = "";
            printer.FooterSpacing = 15;
            printer.PageSeparator = " / ";
            printer.PageText = "页";

            printer.PrintPreviewDataGridView(dgvStaff);
        }

        private void btnOutputStaff_Click(object sender, EventArgs e)
        {
            string f = "staff.xls";
            excelout.ExportExcel(f, dgvStaff);
        }

        private void tsbtnOutput_Click(object sender, EventArgs e)
        {
            string f = "tool.xls";
            excelout.ExportExcel(f, dgvTool);
        }

        private void btnSyncOutput_Click(object sender, EventArgs e)
        {
            string f = "sync.xls";
            excelout.ExportExcel(f, dgvSync);
        }

        private void mToolBase_Click(object sender, EventArgs e)
        {
            if(tbpData.SelectedIndex == 1)
            {
                return;
            }
            tbpData.SelectTab(1);
        }

        private void mManBase_Click(object sender, EventArgs e)
        {
            if (tbpData.SelectedIndex == 2)
            {
                return;
            }
            tbpData.SelectTab(2);
        }

        private void mSyncBase_Click(object sender, EventArgs e)
        {
            if (tbpData.SelectedIndex == 0)
            {
                return;
            }
            tbpData.SelectTab(0);
        }

        private void mAdminBase_Click(object sender, EventArgs e)
        {
            frmAdmin frmA = new frmAdmin();
            frmA.ShowDialog(this);
        }

        private void tbMsg_TextChanged(object sender, EventArgs e)
        {
            tbMsg.SelectionStart = tbMsg.Text.Length;
            tbMsg.ScrollToCaret();
        }
    }
}
